package com.kaaction.modules.market.api;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.kaaction.common.web.BaseController;
import com.kaaction.modules.eb.entity.Product;
import com.kaaction.modules.eb.service.ProductService;
import com.kaaction.modules.market.entity.Event;
import com.kaaction.modules.market.entity.EventChannel;
import com.kaaction.modules.market.service.EventChannelService;
import com.kaaction.modules.market.service.EventService;

@Controller
@RequestMapping(value = "api/v1")
public class EventChannelApiController  extends BaseController{
	
	@Autowired
	private EventChannelService eventChannelService;
	
	@Autowired
	private EventService eventService;
	
	@Autowired
	private ProductService productService;

	@RequestMapping(value = "event-{eventId}-channel-{channelId}")
	public void map(@PathVariable String eventId,@PathVariable String channelId,HttpServletResponse response) throws IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		PrintWriter pw = response.getWriter();
		
		Event event = eventService.get(eventId);
		if(event != null && event.getType().compareTo("900") > 0){
			Product product = event.getProduct();
			if(product != null){
				String productId = event.getProduct().getId();
				product = productService.get(productId);
				event.setProduct(product);
			}
		}
		if(event.getType().compareTo("900") < 0){
			//打开页面时，记录次数
			EventChannel eventChannel = eventChannelService.getByEventAndChannel(eventId,channelId);
			int clickNum = 1 + eventChannel.getClickNum();
			eventChannel.setClickNum(clickNum);
			eventChannelService.save(eventChannel);
		}
		
		
		pw.write(JSON.toJSONString(event,SerializerFeature.DisableCircularReferenceDetect));
		
		pw.flush();
		pw.close();
	}
}
